# 用户健康数据管理的视图文件
from django.shortcuts import render
from django.core.paginator import Paginator
from django.db.models import Q
from myadmin.models import UserBodyRecords, Users  # 关联自定义用户模型

def index(request, pIndex=1):
    """健康数据列表页：通过users表的status筛选（不涉及健康表的status）"""
    ubrlist = UserBodyRecords.objects.select_related('user')  # 关联查询用户表
    mywhere = []

    # 按users表的status筛选（正确关联）
    status = request.GET.get('status', '')
    if status != '':
        ubrlist = ubrlist.filter(user__status=status)  # 仅使用用户表的status
        mywhere.append(f'status={status}')

    # 搜索处理（用户ID、记录日期）
    kw = request.GET.get("keyword", None)
    if kw:
        ubrlist = ubrlist.filter(
            Q(user_id__contains=kw) | 
            Q(record_date__contains=kw)
        )
        mywhere.append(f'keyword={kw}')

    # 排序处理（移除健康表的status排序，保留用户表的status排序）
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        # 允许排序的字段（不含UserBodyRecords的status，因已删除）
        valid_fields = [
            'record_id', 'user_id', 'record_date', 'weight', 'body_fat_percentage',
            'muscle_mass', 'water_percentage', 'bone_mass', 'blood_pressure_systolic',
            'blood_pressure_diastolic', 'blood_sugar', 'user__status'  # 仅用户表的status
        ]
        if sort.lstrip('-') in valid_fields:
            if order == 'desc':
                sort = f'-{sort}'
            ubrlist = ubrlist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])

    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(ubrlist, 5)
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range

    context = {
        "ubrlist": list2,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'current_status': status  # 回显用户表的status筛选条件
    }
    return render(request, "myadmin/userbodyrecords/index.html", context)

# 其他视图函数（add/insert/delete/edit/update）保持不变，确保不涉及UserBodyRecords的status字段
def add(request):
    return render(request, "myadmin/userbodyrecords/add.html")

def insert(request):
    try:
        ob = UserBodyRecords()
        ob.user_id = request.POST.get('user_id')
        ob.record_date = request.POST.get('record_date')
        ob.weight = request.POST.get('weight') if request.POST.get('weight') else None
        ob.body_fat_percentage = request.POST.get('body_fat_percentage') or None
        ob.muscle_mass = request.POST.get('muscle_mass') or None
        ob.water_percentage = request.POST.get('water_percentage') or None
        ob.bone_mass = request.POST.get('bone_mass') or None
        ob.blood_pressure_systolic = request.POST.get('blood_pressure_systolic') or None
        ob.blood_pressure_diastolic = request.POST.get('blood_pressure_diastolic') or None
        ob.blood_sugar = request.POST.get('blood_sugar') or None
        ob.notes = request.POST.get('notes')
        ob.save()  # 不涉及status字段
        context = {'info': "添加成功！"}
    except Exception as err:
        print(err)
        context = {'info': "添加失败！"}
    return render(request, "myadmin/info.html", context)

def delete(request, rid=0):
    try:
        UserBodyRecords.objects.get(record_id=rid).delete()  # 直接删除，不涉及status
        context = {'info': "删除成功！"}
    except UserBodyRecords.DoesNotExist:
        context = {'info': "删除失败：记录不存在！"}
    except Exception as err:
        print(f"删除错误: {err}")
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)

# userbodyrecords.py中的edit函数
def edit(request, rid=0):  # 参数名必须是rid，与URL中的<int:rid>一致
    """加载健康数据编辑表单并显示原始数据"""
    try:
        # 验证rid是否为有效整数（调试用）
        print(f"接收的记录ID：{rid}，类型：{type(rid)}")  # 应输出类似"接收的记录ID：1，类型：<class 'int'>"
        
        # 查询记录
        ob = UserBodyRecords.objects.select_related('user').get(record_id=rid)
        context = {'ubr': ob}
        return render(request, "myadmin/userbodyrecords/edit.html", context)
    
    except UserBodyRecords.DoesNotExist:
        context = {'info': f"没有找到ID为 {rid} 的健康记录"}
        return render(request, "myadmin/info.html", context)
    except Exception as err:
        context = {'info': f"加载失败：{str(err)}"}
        return render(request, "myadmin/info.html", context)

def update(request, rid):
    try:
        ob = UserBodyRecords.objects.get(record_id=rid)
        ob.user_id = request.POST.get('user_id')
        ob.record_date = request.POST.get('record_date')
        ob.weight = request.POST.get('weight') if request.POST.get('weight') else None
        ob.body_fat_percentage = request.POST.get('body_fat_percentage') or None
        ob.muscle_mass = request.POST.get('muscle_mass') or None
        ob.water_percentage = request.POST.get('water_percentage') or None
        ob.bone_mass = request.POST.get('bone_mass') or None
        ob.blood_pressure_systolic = request.POST.get('blood_pressure_systolic') or None
        ob.blood_pressure_diastolic = request.POST.get('blood_pressure_diastolic') or None
        ob.blood_sugar = request.POST.get('blood_sugar') or None
        ob.notes = request.POST.get('notes')
        ob.save()  # 不涉及status字段更新
        context = {'info': "修改成功！"}
    except Exception as err:
        print(err)
        context = {'info': "修改失败！"}
    return render(request, "myadmin/info.html", context)